package com.cloud.salon.client.business.service.impl;

import com.cloud.salon.client.business.repository.RecordItemRepository;
import com.cloud.salon.client.business.service.ItemService;
import com.cloud.salon.client.business.service.RecordItemService;
import com.cloud.salon.client.business.service.RecordService;
import com.cloud.salon.common.base.entity.business.Item;
import com.cloud.salon.common.base.entity.business.Record;
import com.cloud.salon.common.base.entity.business.relation.RecordItem;
import com.cloud.salon.common.base.response.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 记录和项目关联业务处理
 * @Author wolf--LZH
 * @CreateDate 2019/5/3 0003 下午 3:47
 */
@Service
public class RecordItemServiceImpl implements RecordItemService {

    @Autowired
    private RecordItemRepository repository;
    @Autowired
    private RecordService recordService;
    @Autowired
    private ItemService itemService;

    public Res setRecordItems(Integer recordId, List<Integer> itemIdList, List<Integer> preferenceIdList) {
        // 获取要设置的记录实体, 若为空则返回错误信息
        Res<Record> recordRes = recordService.findById(recordId);
        if(recordRes.getData() == null)
            return new Res(-3, "无此记录");

        // 获取所有的item
        Res<List<Item>> itemRes = itemService.findByIdList(itemIdList);
        if(itemRes.getStatus() != 0)
            return new Res(-3, "参数错误,请确保选择的项目存在");

        // 添加当前用户不具备的角色
        int index = 0;
        for (Integer itemId: itemIdList) {
            // 新增实体
            RecordItem save = new RecordItem();
            save.setRecordId(recordId);
            save.setItemId(itemId);

            if (Integer.valueOf(0).equals(preferenceIdList.get(index)))
                save.setPreferenceId(null);
            else
                save.setPreferenceId(preferenceIdList.get(index));

            repository.save(save);
            index++;
        }

        return new Res(0, "操作成功");
    }
}
